﻿<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/jsp/common/taglibs.jsp" %>
<html>
<body class="no-skin" >
<!--输入区域-->
    <div class="widget-box transparent">
        <div class="widget-header widget-header-small">
            <h4 class="widget-title blue smaller">
                <i class="ace-icon fa fa-rss orange"></i>
                岗位信息
            </h4>
            <div class="widget-toolbar">
                <a href="#" class="blue" id="editS" onclick="submitPosEditForm();">
                    <i class="ace-icon fa fa-save "></i>
                    保存岗位信息
                </a>
            </div>
        </div>
        <div class="widget-body">
            <div class="widget-main padding-8">
                <!-- #section:pages/profile.feed -->
                <div id="profile-feed-1" class="profile-feed">
                    <form id="posEditForm" class="form-horizontal" role="form">
                        <div class="space-1">
                            <input name="orgCode" type="hidden" id="orgCode" class="col-xs-6" value="${organ.orgCode}"/>
                            <input name="positionId" type="hidden" id="positionId" class="col-xs-6"
                                   value="${posEntity.positionId}"/>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="form-field-1">所属机构</label>
                            <div class="col-sm-9">
                                <input name="orgName" type="text" disabled="disabled" id="orgName" class="col-xs-6"
                                       value="${organ.orgName}"/>
                            </div>
                        </div>

                        <div class="space-1"></div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="form-field-1">上级岗位</label>
                            <div class="col-sm-9">
                                <input type="text" id="parentCodeStr" name="parentCodeStr" class="col-xs-6" readonly
                                       onclick="showTree(); return false;" value="${posEntity.parentName}"/>
                                <a href="#" class="btn btn-xs btn-info" onclick="clearContent();">
                                    <i class="fa fa-eraser"></i>
                                </a>
                                <input type="hidden" id="parentCode" name="parentCode" class="col-xs-6"
                                       value="${posEntity.parentCode}"/>
                            </div>
                        </div>

                        <div class="space-1"></div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="form-field-1">岗位代码</label>
                            <div class="col-sm-9">
                                <input name="positionCodeStr" type="text" id="positionCodeStr" disabled="disabled"
                                       class="col-xs-6" value="${posEntity.positionCode}"/>
                                <input name="positionCode" type="hidden" id="positionCode" class="col-xs-6"
                                       value="${posEntity.positionCode}"/>
                            </div>
                        </div>

                        <div class="space-1"></div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="form-field-1">岗位名称</label>
                            <div class="col-sm-9">
                                <input type="text" id="positionName" name="positionName" maxlength="100" class="col-xs-6"
                                       value="${posEntity.positionName}"/>
                            </div>
                        </div>

                        <div class="space-1"></div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label no-padding-right" for="form-field-1">描述</label>
                            <div class="col-sm-9">
                                <textarea name="remark" rows="5" class="col-xs-6" id="remark">${posEntity.remark}</textarea>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="widget-box transparent" style=" margin-bottom:0;">
                <div class="widget-header widget-header-small">
                    <h4 class="widget-title blue smaller">
                        <i class="ace-icon glyphicon glyphicon-cog orange"></i>
                        角色维护
                    </h4>

                    <div class="widget-toolbar">
                        <a href="#modal-table" onclick="showRole();" class="blue" id="posRoleShow" data-toggle="modal">
                            <i class="ace-icon glyphicon glyphicon-plus "></i> 添加角色 </a>
                    </div>
                </div>
            </div>

            <div style="overflow-x:auto;   height:260px">
                <table id="position-role-table" class="table table-striped table-bordered table-hover" style="margin:0; ">
                    <thead>
                    <tr>
                        <th align="center" nowrap="nowrap" class="center">序号</th>
                        <th nowrap="nowrap"><strong>角色名称</strong></th>
                        <th nowrap="nowrap">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>

            <div class="col-xs-12" style="text-align:center"><!-- 按钮行-->
                <div class="clearfix form-actions" style="">
                    <button class="btn" type="button" onclick="toBack();">
                        <i class="ace-icon fa fa-undo bigger-110"></i>
                        返 回
                    </button>
                </div>
            </div>

            <div id="modal-table" class="modal fade" tabindex="-1" style=" height:auto; overflow:auto">
                <div class="modal-dialog" style="width:90%;height:auto">
                    <div class="modal-content">
                        <div class="modal-header no-padding">
                            <div class="table-header">
                                角色选择
                                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                    <span class="white">&times;</span>
                                </button>
                            </div>
                        </div>

                        <div class="modal-body no-padding">
                            <table style="width:100%" border='0'>
                                <tr>
                                    <td width='12%' align='right' nowrap='nowrap'><strong>角色名称：</strong></td>
                                    <td width='43%'><input name='roleName' type='text' id='roleName' class='col-xs-12'
                                                           maxlength="100"/></td>
                                    <td width='45%' align='left' nowrap='nowrap'>
                                        <button class='btn btn-sm ' type='button' style='height:30px; line-height:10px'
                                                onclick="initRoleTable();"> 查 询
                                        </button>
                                    </td>
                                </tr>
                            </table>
                            <div style="overflow-y:auto; height:300px; width:100%">
                                <table id="role-list-table"
                                       class="table table-striped table-bordered table-hover no-margin-bottom no-border-top"
                                       style="min-width:100%">
                                    <thead>
                                    <tr>
                                        <th>
                                            <span class="center">
                                                <input type="checkbox" id="checkAll" name="checkAll"
                                                       onclick="checkAll(this);"/>
                                            </span>
                                        </th>
                                        <th>角色名称</th>
                                        <th>描术</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-xs-12" style="text-align:center; background:#fff; padding:0; height:40px; ">
                                <!-- 按钮行-->
                                <button class="btn btn-info btn-sm" type="button" data-dismiss="modal" onclick="subPosRole();">
                                    <i class="ace-icon fa fa-check "></i> 选 取
                                </button>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="menuContent" class="menuContent" style="display:none; position: absolute;">
        <ul id="treeDemo" class="ztree" style="margin-top:0;"></ul>
    </div>

    <script src="${resRoot}/plugin/ace-v1.3/assets/js/jquery.validate.min.js"></script>
    <script src="${resRoot}/plugin/jquery-validation/localization/messages_zh.js"></script>
    <script type="text/javascript">
        //返回
        function toBack() {
            var orgCode = $("#orgCode").val();
            window.location.href = "../../auth/position/toPosList.htm?orgCode=" + orgCode;
        }

        var setting = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: "positionCode",
                    pIdKey: "parentCode",
                    rootPId: null
                },
                key: {
                    name: "positionName"
                }
            },
            view: {
                selectedMulti: false
            },
            callback: {
                onClick: onClick
            }
        };

        //点击
        function onClick(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    nodes = zTree.getSelectedNodes(),
                    v = "";
            val = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v = nodes[i].positionName;
                val = nodes[i].positionCode;
            }

            $("#parentCodeStr").val(v);
            $("#parentCode").val(val);

        }


        //显示下拉树
        function showTree() {
            var posObj = $("#parentCodeStr");
            var posOffset = $("#parentCodeStr").offset();
            $("#menuContent").css({
                left: posOffset.left + "px",
                top: posOffset.top + posObj.outerHeight() + "px"
            }).slideDown("fast");

            $("body").bind("mousedown", onBodyDown);
        }

        //隐藏下拉树
        function hideMenu() {
            $("#menuContent").fadeOut("fast");
            $("body").unbind("mousedown", onBodyDown);
        }


        function onBodyDown(event) {
            if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
                hideMenu();
            }
        }


        //得到树
        $(document).ready(function () {
            var orgCode = $("#orgCode").val();
            var positionCode = $("#positionCode").val();
            $.ajax({
                type: "POST",
                //contentType: 'application/json',
                dataType: "json",
                data: {orgCode: orgCode, positionCode: positionCode},
                url: contextPath + "/auth/position/getPositionByOrg.json",
                success: function (data) {
                    $.fn.zTree.init($("#treeDemo"), setting, data);
                },
                error: function () {
                    $.Alert("系统错误！");
                }
            });
            initTable();
        });

        //清除上级岗位
        function clearContent() {
            $("#parentCodeStr").val("");
            $("#parentCode").val("");
        }

        //根据岗位代码查询角色信息列表
        function initTable() {
            $("#position-role-table").dataTable().fnDestroy();
            json = {};
            json.bPaginate = false;
            json.bInfo = false;
            json.showLineNuber = true;
            json.id = "position-role-table";
            json.url = contextPath + '/auth/role/getPositionRoleList.json';
            json.param = [
                {"name": "positionCode", "value": $.trim($("#positionCode").val())}
            ];
            json.columns = [{"sWidth": "20px", "sClass": "text-center"},
                {"mData": "roleName", "sWidth": "100px", "sClass": "text-center"},
                {
                    "mData": "roleCode", "sWidth": "100px", "sClass": "text-center",
                    "mRender": function (data, type, row) {
                        if (data) {
                            return '&nbsp;&nbsp;<a style="color:#428bca" href="javascript:toDeletePosRole(\'' + data + '\')" >删除</a>&nbsp;&nbsp;';
                        }
                    }
                }
            ];
            var oTable1 = TableManagedEdit(json).init();
        }

        function toDeletePosRole(roleCode) {
            $.Confirm('请确认是否移除该角色？', '', function () {
                deletePosRole(roleCode);
            });
        }

        function deletePosRole(roleCode) {
            var positionCode = $("#positionCode").val();
            $.ajax({
                url: contextPath + "/auth/position/deletePositionRole.json",
                type: "post",
                data: {positionCode: positionCode, roleCode: roleCode},
                async: false,
                success: function (data) {
                    var msg = eval("(" + data + ")");
                    $.Alert(msg.message, '', initTable);
                },
                error: function () {
                    //$.Alert("服务异常，请稍后尝试！");
                }
            });
        }

        var TableManagedEdit = function (param) {
            return {
                //main function to initiate the module
                init: function () {
                    if (!jQuery().dataTable) {
                        return;
                    }
                    var datatable = $('#' + json.id).dataTable(
                            {
                                "bFilter": !json.bFilter ? false : true,
                                "bSort": !json.bSort ? false : true,
                                "bProcessing": !json.bProcessing ? false : true,
                                "sAjaxSource": json.url,
                                "fnServerParams": function (aoData) {
                                    $.each(json.param, function (i, item) {
                                        aoData.push(item);
                                    });
                                },
                                "sServerMethod": "post",
                                "bServerSide": true,
                                "aoColumns": json.columns ? json.columns : null,
                                //"aLengthMenu" : [ [ 10, 20, 50 ], [ 10, 20, 50 ] ],
                                "bPaginate": false,
                                "bInfo": false,
                                "iDisplayLength": 1000,
                                "bLengthChange": !json.bLengthChange ? false
                                        : true,
                                "sPaginationType": "bootstrap",
                                "aaSorting": json.aaSorting ? json.aaSorting : '',
                                "aoColumnDefs": [{
                                    "sDefaultContent": '',
                                    "aTargets": ["_all"]
                                }],

                                "fnCreatedRow": function (nTr, data, iRow, iTotal) {
                                    if (param.showLineNuber) {
                                        if (nTr) {
                                            nTr.cells[0].innerHTML = (iRow + 1);
                                        }
                                    }
                                },
                                "fnServerData": function (sSource, aoData,
                                                          fnCallback) {
                                    $.ajax({
                                        "dataType": 'json',
                                        "type": "POST",
                                        "url": sSource,
                                        "data": aoData,
                                        "success": fnCallback,
                                        "timeout": 3000000,
                                        "error": function handleAjaxError(xhr,
                                                                          textStatus, error) {
                                            if (textStatus == "timeout") {
                                                $.Alert("连接超时!请稍后再试!!!");
                                            } else if (textStatus == "error") {
                                                $.Alert("系统繁忙!!!,请稍后再试!!!");
                                            }
                                            datatable.fnProcessingIndicator(false);
                                        }
                                    });
                                },
                                "oLanguage": json.pageInfo ? json.pageINfo : {
                                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                                    "sZeroRecords": "抱歉， 没有找到",
                                    "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                                    "sInfoEmpty": " ",
                                    "sProcessing": "正在查询....",
                                    "sInfoFiltered": "",
                                    "oPaginate": {
                                        "sFirst": "首页",
                                        "sPrevious": "前一页",
                                        "sNext": "后一页",
                                        "sLast": "尾页"
                                    }
                                }
                            });
                    return datatable;
                }
            };

        };

        //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外
        function forbidBackSpace(e) {
            var ev = e || window.event; //获取event对象
            var obj = ev.target || ev.srcElement; //获取事件源
            var t = obj.type || obj.getAttribute('type'); //获取事件源类型
            //获取作为判断条件的事件类型
            var vReadOnly = obj.readOnly;
            var vDisabled = obj.disabled;
            //处理undefined值情况
            vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;
            vDisabled = (vDisabled == undefined) ? true : vDisabled;
            //当敲Backspace键时，事件源类型为密码或单行、多行文本的，
            //并且readOnly属性为true或disabled属性为true的，则退格键失效
            var flag1 = ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") && (vReadOnly == true || vDisabled == true);
            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效
            var flag2 = ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea";
            //判断
            if (flag2 || flag1) return false;
        }
        //禁止后退键 作用于Firefox、Opera
        document.onkeypress = forbidBackSpace;
        //禁止后退键  作用于IE、Chrome
        document.onkeydown = forbidBackSpace;

        //提交表单函数
        function submitPosEditForm() {
            if (validateForm()) {
                $.ajax({
                    url: contextPath + "/auth/position/editPosition.json",
                    type: "post",
                    data: $("#posEditForm").serialize(),
                    async: false,
                    success: function (data) {
                        var msg = eval("(" + data + ")");
                        $.Alert(msg.message);
                    },
                    error: function () {
                        //$.Alert("服务异常，请稍后尝试！");
                    }
                });
            }
        }

        //客户简称验证
        //jQuery.validator.addMethod("dealerShtNameCheck",function(value,element){
        //  var reg = /^[0-9a-zA-Z]+$/;
        // return this.optional(element) || reg.test(value);
        //},"客户简称只能为字母或数字");

        //表单验证函数
        function validateForm() {
            return $("#posEditForm").validate({
                errorElement: 'span',
                errorClass: 'help-block',
                focusInvalid: false,
                rules: {
                    "positionName": {
                        required: true
                    },
                    "remark": {
                        maxlength: 500
                    }
                },

                highlight: function (e) {
                    $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
                },

                success: function (e) {
                    $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
                    $(e).remove();
                },


                errorPlacement: function (error, element) {
                    if (element.is(':checkbox') || element.is(':radio')) {
                        var controls = element.closest('div[class*="col-"]');
                        if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                        else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
                    }
                    else if (element.is('.select2')) {
                        error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
                    }
                    else if (element.is('.chosen-select')) {
                        error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
                    }
                    else if (element.is('textarea')) {
                        error.appendTo(element.parent());
                    }
                    else if (element.is('input[type=text]')) {
                        error.appendTo(element.parent());
                    }
                    else error.insertAfter(element.parent());
                }
            }).form();
        }

        //隐藏层
        //显示隐藏层的数据
        function showRole() {
            initRoleTable();
        }

        function initRoleTable() {
            $("#role-list-table").dataTable().fnDestroy();
            json = {};
            json.bPaginate = false;
            json.bInfo = false;
            json.showLineNuber = false;
            json.id = "role-list-table";
            json.url = contextPath + '/auth/role/getRoleListData.json';
            json.param = [{"name": "roleName", "value": $.trim($("#roleName").val())},
                {"name": "positionCode", "value": $.trim($("#positionCode").val())}
            ];
            json.columns = [{
                "mData": "roleCode", "sWidth": "100px", "sClass": "text-center",
                "mRender": function (data, type, row) {
                    return '<input type="checkbox" name="roleCheck" value="' + data + '" onclick="checkOne(this);" />';
                }
            },
                {"mData": "roleName", "sWidth": "100px", "sClass": "text-center"},
                {"mData": "remark", "sWidth": "100px", "sClass": "text-center"}
            ];
            var oTable1 = TableManagedEdit(json).init();
        }

        //全选
        function checkAll(that) {
            $("input[name='roleCheck']").each(function () {
                this.checked = that.checked;
            });
        }

        //单选
        function checkOne(that) {
            var numAll = $("input[name='roleCheck']").length;
            var numCheck = 0;
            $("input[name='roleCheck']").each(function () {
                if (this.checked == that.checked) {
                    numCheck++;
                }
            });
            if (numAll == numCheck) {
                if (that.checked) {
                    $("#checkAll").prop("checked", true);
                }
            } else {
                if (!that.checked) {
                    $("#checkAll").attr("checked", false);
                }
            }
        }

        //选取角色 添加岗位角色关系
        function subPosRole() {
            var codeArr = new Array();
            $("input[name='roleCheck']:checked").each(function () {
                codeArr.push(this.value);
            });
            if (codeArr.length < 1) {
                $.Alert("请选择角色！");
                return;
            }
            var roleCodeStr = codeArr.join(",");
            savePositionRole(roleCodeStr);
        }

        //保存岗位角色关系
        function savePositionRole(params) {
            var positionCode = $("#positionCode").val();
            $.ajax({
                url: contextPath + "/auth/position/savePositionRole.json",
                type: "post",
                data: {positionCode: positionCode, params: params},
                async: false,
                success: function (data) {
                    var msg = eval("(" + data + ")");
                    $.Alert(msg.message, '', initTable);
                },
                error: function () {
                    //$.Alert("服务异常，请稍后尝试！");
                }
            });
        }
    </script>
</body>
</html>
